import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { RechargeFlow } from './rechargeFlow.entity';
import utils from 'src/common/utils';

@Injectable()
export class RechargeFlowService {
  constructor(
    @InjectRepository(RechargeFlow)
    private rechargeFlowRepository: Repository<RechargeFlow>,
  ) {}

  async findMyRechargeFlow(skip: number, take: number, wx_user: string): Promise<{data: RechargeFlow[], total: number}>{
    let data = await this.rechargeFlowRepository.query(`
      select amount, status, create_time, update_time
      from recharge_flow
      where wx_user = ? and recharge_flow.status = 1
      order by update_time desc,create_time desc
      limit ?,?
    `,[wx_user, skip, take])
    let total = await this.rechargeFlowRepository.query(`
      select count(1) as total
      from recharge_flow
      where wx_user = ? and recharge_flow.status = 1
    `,[wx_user])
    data.map(e => {
      if(e.update_time){
        e.update_time = e.update_time.getTime()
        delete e.create_time
      }
      if(e.create_time){
        e.create_time = e.create_time.getTime()
      }
      if(!utils.validIsNull(e.amount)){
        e.amount = Number(e.amount) / 100
      }
    })
    return {data, total: total[0].total}
  }

  async findTotalAmountSuccessByWxUserStatisticsDay(skip: number, take: number, wx_user: string): Promise<{data: RechargeFlow[], total: number, totalPrice: number}>{
    let data = await this.rechargeFlowRepository.query(`
      select substring(a.update_time, 1, 10) update_time,sum(a.amount) totalPrice from recharge_flow a
      where a.status = 1 and a.wx_user = ?
      group by substring(a.update_time, 1, 10)
      order by substring(a.update_time, 1, 10) desc
      limit ?,?
    `,[wx_user, skip, take])

    let total = await this.rechargeFlowRepository.query(`
      select count(1) as total from (
        select substring(a.update_time, 1, 10) update_time from recharge_flow a
        where a.status = 1 and a.wx_user = ?
        group by substring(a.update_time, 1, 10)
        order by substring(a.update_time, 1, 10) desc
      ) recharge_flow
    `,[wx_user, skip, take])

    let totalPrice = await this.rechargeFlowRepository.query(`
      select sum(amount) as amount
      from recharge_flow
      where wx_user = ?
        and status = 1
    `,[wx_user])

    return {data, total: Number(total[0].total || 0), totalPrice: totalPrice[0].amount || 0}
  }
}
